package com.yu.admin.modules.auth.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.yu.common.constant.Const;
import com.yu.common.service.RedisService;
import com.yu.common.util.result.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;

@Slf4j
@Api("验证码")
@RestController
@RequestMapping("/api-system/auth")
public class VerifyCodeController {

    @Resource
    private RedisService redisService;

    private static DefaultKaptcha verifyCodeProducer;

    static {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        // 字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        // 图片宽
        properties.setProperty("kaptcha.image.width", "100");
        // 图片高
        properties.setProperty("kaptcha.image.height", "35");
        // 字体大小
        properties.setProperty("kaptcha.textproducer.font.size", "35");
        // 字体
        properties.setProperty("kaptcha.textproducer.font.names", "楷体,微软雅黑,宋体");
        // 文本集合，验证码值重其中生成
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
        // 验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", "2");

        defaultKaptcha.setConfig(new Config(properties));
        verifyCodeProducer = defaultKaptcha;
    }

    @ApiOperation(value = "生成验证码")
    @GetMapping("/code")
    public R generateVerifyCode() throws Exception {
        String createText = verifyCodeProducer.createText();
        String uuid = UUID.randomUUID().toString();
        redisService.set(Const.CONST_verify_code_redis_prefix + uuid, createText, 30);

        // 转换流信息写出
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        ImageIO.write(verifyCodeProducer.createImage(createText), "jpg", outputStream);

        log.info("[生成的验证码]" + createText);
        return R.ok(new HashMap<String, String>() {{
            put("uuid", uuid);
            // 手动拼接上 data:image/jpeg;base64, 这是base64图片编码格式!!!
            put("image", "data:image/jpeg;base64," + Base64Utils.encodeToString(outputStream.toByteArray()));
        }});
    }
}
